package com.zhanggm.s3.user.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhanggm.s3.core.exception.BizException;
import com.zhanggm.s3.core.utils.AjaxResult;
import com.zhanggm.s3.core.utils.JwtUtils;
import com.zhanggm.s3.user.entity.User;
import com.zhanggm.s3.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 认证 授权
     * @param user
     * @return
     */
    @PostMapping("login")
    public AjaxResult login(@RequestBody User user) {
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
            throw new BizException(400, "用户名或密码不能为空");
        }
        //查询用户信息
        User loginUser = iUserService.getByUsername(user.getUsername());
        if (loginUser == null) {
            throw new BizException(400, "用户不存在");
        }

        //判断密码是否正确
        if (!user.getPassword().equals(loginUser.getPassword())) {
            throw new BizException(400, "用户名或密码不能为空");
        }
        //令牌token，每次登录都是唯一，可以用uuid来生成
        String token = jwtUtils.createToken(JSON.toJSONString(loginUser));
        return AjaxResult.success("登录成功",token);
    }

}
